{% extends "layout.html" %}

{% block breadcrumb %}
<li><a href="#">用户管理</a><span class="divider"></span></li>
<li class="active">用户列表</li>
{% endblock %}

{% block body %}
<div class="widget-box">
   <div class="widget-title"> 
      <h5 style="float:left;"><i class="fa fa-table fa-fw"></i>用户列表</h5>
      <button style="float:right;" class="btn btn-primary btn-sm" id="addBtn">添加用户</button>
   </div> <!--widget-title end-->
    
<!--添加用户模态窗-->
<div id="addModal" class="modal fade">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
		<h4 class="modal-title">添加用户</h4>
	  </div><!--modal-header end-->

    <div class="modal-body">
    <form class="form-horizontal" id="addForm" accept-charset="UTF-8">
    <div class="control-group">
        <label class="control-label col-sm-3">用户名：</label>
        <div class="col-sm-9">
         <input type="text" name="username" class="form-control"  datatype="s5-16" errormsg="必须是5-16个字符" />
        </div>
    </div> <!--用户名添加-->
    <div class="control-group">
        <label class="control-label col-sm-3">中文名：</label>
        <div class="col-sm-9">
            <input  type="text" name="name" class="form-control" datatype="zh2-4" errormsg="必须是2-4个中文字符" />
        </div> 
    </div><!--中文名添加-->
    <div class="control-group">
		<label class="control-label col-sm-3">角色: </label>
		<div class="col-sm-9">
                <select id="r_id" name="r_id" class="form-control multiselect" datatype="*" errormsg="角色不能为空" multiple="multiple" >
                   </select>
		</div >  
	</div> <!--选择角色-->
    <div class="control-group">
        <label  class="control-label col-sm-3">E-mail：</label>
        <div class="col-sm-9">
            <input  type="email"  name="email" class="form-control"  datatype="e" errormsg="Email格式不正确" />
        </div>
    </div><!--Email添加-->
    <div class="control-group">
        <label class="control-label col-sm-3">手机：</label>
        <div class="col-sm-9">
            <input type="text" name="mobile" class="form-control" datatype="m" errormsg="手机格式不对"  />
        </div>   
    </div><!--手机添加-->
    <div class="control-group">
        <label class="control-label col-sm-3">状态：</label>
        <div class="col-sm-9">
            <select name='is_lock' class="form-control"  style='width:120px'> 
                 <option value=0>正常</option>
                 <option value=1>锁定</option>
              </select>
        </div>   
    </div>  <!--状态选择-->
    <div class="control-group">
        <label class="control-label col-sm-3">登录密码：</label>
        <div class="col-sm-9">
             <input  type="password" name="password" class="form-control"  datatype="*6-15" errormsg="密码需要6~15位之间" />
        </div>   
    </div> <!--登录密码-->
    <div class="control-group">
        <label  class="control-label col-sm-3">再次输入：</label>
        <div class="col-sm-9">
               <input  type="password" name="repwd" class="form-control"  datatype="*" recheck="password" errormsg="您两次输入的账号密码不一致！" />
        </div> 
    </div> <!--重新输入密码-->
    <div class="form-group">
         <div class="modal-footer">
                <button class="btn btn-primary" id="submitbtn" >确认添加</button>
				<button class="btn btn-warning" data-dismiss="modal">退出</button>
        </div>
    </div>
    </form> 

      </div><!-- /.modal-body-->
   </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<!--更新用户模态窗-->
<div id="updateModal" class="modal fade">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
		<h4 class="modal-title">更新用户信息</h4>
	  </div><!--modal-header end-->

    <div class="modal-body">
    <p hidden id="uperrorMsg" class="text-danger" style="color:red"></p> <!-- foe error msg-->
    <form class="form-horizontal" id="updateForm" accept-charset="UTF-8">
    
    <input type="hidden" id='upid' name="id">  <!--update need id-->
    <div class="control-group">
        <label class="control-label col-sm-3">用户名：</label>
        <div class="col-sm-9">
         <input type="text" name="username" id="upusername" class="form-control"  datatype="s5-16" errormsg="必须是5-16个字符" />
        </div>
    </div> <!--用户名添加-->
    <div class="control-group">
        <label class="control-label col-sm-3">中文名：</label>
        <div class="col-sm-9">
            <input  type="text" name="name" id="upname"  class="form-control" datatype="zh2-4" errormsg="必须是2-4个中文字符" />
        </div> 
    </div><!--中文名添加-->
    <div class="control-group">
		<label class="control-label col-sm-3">角色: </label>
		<div class="col-sm-9">
                <select id="upr_id" name="r_id" class="form-control multiselect" datatype="*" errormsg="角色不能为空" multiple="multiple" >
                   </select>
		</div >  
	</div> <!--选择角色-->
    <div class="control-group">
        <label  class="control-label col-sm-3">E-mail：</label>
        <div class="col-sm-9">
            <input  type="email" id="upemail" name="email" class="form-control"  datatype="e" errormsg="Email格式不正确" />
        </div>
    </div><!--Email添加-->
    <div class="control-group">
        <label class="control-label col-sm-3">手机：</label>
        <div class="col-sm-9">
            <input type="text" id="upmobile" name="mobile" class="form-control" datatype="m" errormsg="手机格式不对"  />
        </div>   
    </div><!--手机添加-->
    <div class="control-group">
        <label class="control-label col-sm-3">状态：</label>
        <div class="col-sm-9">
            <select id='upis_lock' name='is_lock' class="form-control"  style='width:120px'> 
                 <option value=0>正常</option>
                 <option value=1>锁定</option>
              </select>
        </div>    
    </div>  <!--状态选择-->
    <div class="form-group">
         <div class="modal-footer">
                <button class="btn btn-primary" id="upbtn" >确认更新</button>
				<button class="btn btn-warning" data-dismiss="modal">退出</button>
        </div>
    </div>
    </form> 
   
     </div><!-- /.modal-body-->
   </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<!--修改用户密码模态窗-->
<div id="ChangePasswdModal" class="modal fade">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
		<h4 class="modal-title">更改用户密码</h4>
	  </div><!--modal-header end-->

      <div class="modal-body">
      <p hidden id="errorMsg" class="text-danger" style="color:red">更改用户密码</p> <!-- foe error msg-->
        <form class="form-horizontal" id="ChangePasswdForm">
        <input id="passwdid" type="hidden"  name="passwdid">  <!--update need id-->
     	<div class="form-group">
            <label class="col-sm-2 control-label">新密码</label>
     		 <div class="col-sm-10">
       		 	<input class="form-control" type="password"  name="changepasswd" />
      		</div> 
        </div>
    	<div class="form-group">
     		<div class="modal-footer">
				<button class="btn btn-primary" >更新</button>
				<button class="btn btn-warning" data-dismiss="modal">退出</button>
         	</div> 
      </div><!--button end-->
     </form>
   </div><!-- /.modal-body-->
   </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

    <div class="widget-content">
    <!--用户列表-->
 		<table id ="datatable"  class="table table-bordered table-striped table-hover">
		<thead>
			<tr>
				<th>用户名</th>
				<th>中文名</th>
				<th>E-mail</th>
				<th>手机</th>
				<th>状态</th>
				<th>角色</th>
				<th>操作</th>
			</tr>
		</thead> 
		<tbody>
		</tbody>
	   </table>
	</div><!--widget-content end-->

</div><!--widget-box end-->
{% endblock %}

{% block js %}
name='user'
function datatable(){
    $('#datatable').DataTable({
        "language": {
            "lengthMenu": "每页 _MENU_ 条记录",
            "zeroRecords": "没有找到记录",
            "sInfo": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 ),显示第 _START_ 至 _END_ 项(总共 _TOTAL_ 项)",
            "infoEmpty": "无记录",
            "infoFiltered": "(从 _MAX_ 条记录过滤)",
            "sSearch": "搜索:",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "末页"
            }
        }
    });
};
/* list all data*/
function list(){
    url = "/listapi?method="+name
    $.getJSON(url,function(data){
       data=JSON.parse(data['result']); //object 
       console.log(data)   //Object {count: 3, code: 0, users: Array[3]}
       if (data['code']== 0){       
           var str = ''
           $.each(data.users,function(k,v){   
               if (v['is_lock']==0){
                   v['is_lock']="正常"
               }else{
                   v['is_lock']="锁定"
               } 
               str +='<tr class="odd gradeX">'+  
               '<td>'+v['username']+'</td>'+  
               '<td>'+v['name']+'</td>'+  
               '<td>'+v['email']+'</td>'+  
               '<td>'+v['mobile']+'</td>'+ 
               '<td><span style="color:#5EDF47;">'+v['is_lock']+'</span></td>'+ 
               '<td>'+v['r_id']+'</td>'+ 
               '<td>'+
               '<button class="btn btn-primary btn-sm update-btn" data-id="'+v['id']+'">更新</button>'+
               '<button class="btn btn-info btn-sm passwd-btn" data-id="'+v['id']+'">修改密码</button>'+
               '<button class="btn btn-danger btn-sm delete-btn" data-id="'+v['id']+'">删除</button>'+
               '</td>'+ '</tr>'          
           })       
                $("tbody").html(str)
                 datatable()
            }else{
                swal("error", data['errmsg'],"error")
            }
         })
}
list()



/*列出角色的信息，并拼接成复选框*/
function rolelist(){
	var url = "/listapi?method=role"
	$.getJSON(url, function(data){
		data=JSON.parse(data['result'])
		console.log(data)	
        if (data['code']== 0){
            var str = ''
            $.each(data.result, function(k,v){
                str += '<option value="'+v['id']+'">'+v['name']+'</option>'
            })
            $("#r_id").html(str)
            $('#r_id').multiselect({maxHeight:200, enableCaseInsensitiveFiltering: true})
            $("#r_id").multiselect('refresh')
        }else{
            swal({
                title:"error", 
                text:data['errmsg'],
                type:"error"
                },function(){
                    location.href="/login"
                });
        } //if end
	})

}
/*点击按钮，显示添加用户模态窗*/
$("#addBtn").on('click',function(){
    rolelist()
    $('#addModal').modal('show')
})
/*检查表单数据是否合法*/
$("#addForm").Validform({
    btnSubmit:"#submitbtn",
    tiptype:3, 
    datatype:{
        "zh2-4" : /^[\u4E00-\u9FA5\uf900-\ufa2d]{2,4}$/,
    }
})
/*用户添加*/
$('#addForm').on('submit',function(){
        var str = $('#addForm').serialize()
        var data={'method':name,'formdata':str}
        $.post('/addapi',data,function(data){ 
            data=JSON.parse(data);   //将json串转换为对象，然后取值
            data = JSON.parse(data['result']) //object
            console.log(data)
            if (data['code']==0){
                    swal({
                        title:"success", 
                        text:"添加用户成功",
                        type:"success",
                        confirmButtonText:'确定'
                        },function(){
                            $('#addModal').modal('hide')
                            window.location.reload();
                         })
            }else{
                swal("error","创建用户失败," + data['errmsg'],"error")
             }   /*if end*/
         })  /*post end*/
         return false;
})  /*submit end*/



/*修改用户密码*/
$("tbody").on('click','.passwd-btn',function(){
    var id = $(this).attr('data-id')
    $('#passwdid').val(id) 
    $('#ChangePasswdModal').modal('show')
})
$('#ChangePasswdForm').on('submit',function(){
    var str = $('#ChangePasswdForm').serialize()
    var url = '/user/changepasswd'
    $.post(url,str,function(result){
        result = JSON.parse(result)
        if (result['code']==0){
            swal({
                title:"success",
                text:"密码更新成功",
                type:"success",
                confirmButtonText:'确定'
                },function(){
                    $('#ChangePasswdModal').modal('hide')
                })
        }else{
            $('#errorMsg').html('failed '+result['errmsg']).show()
        }
    })
    return false
})

/*点击按钮，显示更新用户模态窗,并获取用户的信息*/
$("tbody").on('click','.update-btn',function(){
    var id = $(this).attr('data-id')
    var url = "/getapi?method="+name+"&id="+id
    $.getJSON(url,function(data){
      data = JSON.parse(data['result'])
      if (data['code']==0){
          $('#upid').val(data['result']['id'])
          $('#upusername').val(data['result']['username'])
          $('#upname').val(data['result']['name'])
          $('#upemail').val(data['result']['email'])
          $('#upmobile').val(data['result']['mobile'])
          $('#upis_lock').val(data['result']['is_lock'])
          s_rolelist(id)
          $('#updateModal').modal('show')
      }else{
          swal("Error", data['errmsg'], "error")
      }
    })
})
/*获取用户所属的角色，拼接为下拉列表*/
function s_rolelist(id){
    var url = "/getapi?method=selected&id="+id+"&m_table=user&field=r_id&s_table=role"
    $.getJSON(url, function(data){
        data=JSON.parse(data['result'])
        console.log(data)
        var str=''
        $.each(data.result, function(k,v){
            console.log(k,v)
            str +='<option value='+v['id']+" "+v['selected']+'>'+v['name']+
            '</option>'
        })
        console.log(str)
        $("#upr_id").html(str)
        $('#upr_id').multiselect({maxHeight:200, enableCaseInsensitiveFiltering: true})
        $('#upr_id').multiselect('refresh');
    })

}

/*检查表单数据是否合法*/
$("#updateForm").Validform({
    btnSubmit:"#upbtn",
    tiptype:3, 
    datatype:{
        "zh2-4" : /^[\u4E00-\u9FA5\uf900-\ufa2d]{2,4}$/,
    }
})


/*更新用户信息*/
$('#updateForm').on('submit',function(){
        var str = $('#updateForm').serialize()
        var data = {'method':name,'formdata':str}
        $.post('/updateapi',data, function(data){  // data is string
            data = JSON.parse(data)    //object
            data = JSON.parse(data['result']) //object
            console.log(data)
            if (data['code']==0){   
            swal({
                title:"success",
                text:"更新成功",
                type:"success",
                confirmButtonText:'确定'
                },function(){
                    $('#updateModal').modal('hide')
                    location.reload()
                })
            }else{
                $('#uperrorMsg').html('Failed: '+data['errmsg']).show()
            }
        })
            return false   //get data and end
})  //submit form

/*删除用户*/
$("tbody").on('click','.delete-btn',function(){
	if(confirm("是否确认删除？")){
		var id = $(this).attr('data-id')
		var url =  "/deleteapi?method="+name+"&id="+id
        console.log(url)
		$.getJSON(url,function(data){
            data = JSON.parse(data['result'])
			if (data['code']== 0 ){
                swal({
                    title:"success",
                    text:"删除成功",
                    type:"success",
                    confirmButtonText:'删除成功'
                    },function(){
                        location.reload()
                    })
 				
			}else{
				swal(data['errmsg'])
			}
    	})
    }  // end confirm
})   
{% endblock %}
